package com.aios.action.user.group;

import com.aios.service.ExistValidationEnum;

public class UserGroupSaveAction extends AbstractUserGroupAction {

	private static final long serialVersionUID = 1L;

	public String execute() {
		commonValidation();
		if (hasErrors()) {
			return INPUT;
		}

		try {
			if (this.mode == Mode.ADD) {
				ExistValidationEnum existValidationEnum = userGroupService
						.validateUserGroupName(userGroup.getGroupName());

				if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					addActionError(getText("group.name.exist"));
					return INPUT;
				}
				userGroupService.save(userGroup, getSessionUserVariable()
						.getId());
			} else {
				
				ExistValidationEnum existValidationEnum = userGroupService
						.validateUserGroupName(userGroup.getGroupName(),userGroup.getId());

				if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					addActionError(getText("group.name.exist"));
					return INPUT;
				}
				userGroupService.update(userGroup, getSessionUserVariable()
						.getId());
			}
		} catch (Exception e) {
			// logger
			addActionError(getText("error.save"));
			return INPUT;
		}

		return SUCCESS;
	}

	private void commonValidation() {

		if (userGroup.getGroupName().isEmpty()) {
			addFieldError("userGroup.groupName",
					getText("error.group.name.empty"));
		}

		if (this.mode == Mode.ADD) {
			addValidation();
		} else if (this.mode == Mode.EDIT) {
			editValidation();
		} else {

		}
	}

	private void addValidation() {
		if (userGroup.getId() != null) {
			addActionError("door.error.id.exist");
		}
	}

	private void editValidation() {
		if (userGroup.getId() == null) {
			addActionError("door.error.id.not.exist");
		}
	}
}
